package com.ubao.activity;

import java.util.ArrayList;
import java.util.List;

import android.app.Activity;
import android.app.AlertDialog;
import android.content.DialogInterface;
import android.content.Intent;
import android.os.Bundle;
import android.os.Handler;
import android.os.Message;
import android.view.KeyEvent;
import android.view.View;
import android.view.View.OnClickListener;
import android.widget.AdapterView;
import android.widget.Button;
import android.widget.TextView;
import android.widget.AdapterView.OnItemClickListener;

import com.ubao.R;
import com.ubao.activity.MyApp.GoBack;
import com.ubao.base.RequestBaseActivity;
import com.ubao.bean.Following;
import com.ubao.network.HttpHandler;
import com.ubao.network.RequestInterface;
import com.ubao.network.ResponseInterface;
import com.ubao.network.Url;
import com.ubao.network.req.SpecialRequest;
import com.ubao.network.resp.NewInfoResponse;
import com.ubao.network.resp.SpecialResponse;
import com.ubao.network.resp.StructResponse;
import com.ubao.ui.bottommenu.BottomMenu;
import com.ubao.ui.pullToRefreshListView.MyListView;
import com.ubao.ui.pullToRefreshListView.NewsRefreshListener;
import com.ubao.ui.pullToRefreshListView.PullToRefreshCallBack;
import com.ubao.ui.pullToRefreshListView.adapter.FollowingsAdapter;
import com.ubao.ui.titlebar.GTitleBar;
import com.ubao.util.Drawer;
import com.ubao.util.ScreenReceiver;
import com.ubao.util.log.Logger;
/**
 * 麦友
 */
public class MaiFriend extends RequestBaseActivity implements OnItemClickListener,OnClickListener,NewsRefreshListener{
	// 网络请求资源的url，和页码
	//private static final String NEWS_URL = "guba.eastmoney.com/get_code_by_xml2.aspx?code=licai&num=20&page=";

	// 信息的ID号
	private static final int MSG_ID = 1111;
	private static final int RECORD_INCREMENT = 20;

	private String TAG = "NES_LIST";

	// 传向ListView的Adapter的数据
	private ArrayList<Following> dataList;
	private String[] linkArray;
	private String[] timeArray;
	private String[] titleArray;
	private String[] sourceArray;
	private String[] commentIdArray;

	private BottomMenu mBottomMenu;
	private MyListView newList;
	private GTitleBar titleBar;

	// 自定义RefreshListView的adapter
	private FollowingsAdapter adapter;

	// 当前的数据分页的页数
	private int pageID = 1;
	// 当前所有数据条数
	private int totalRecord;

	// 判断从响应中读取数据是否成功
	private boolean readDataSuccess = true;
	// 判断是否是按下ListView中的更多按钮
	private boolean isMore = false;
	// 得到全局数据
	private MyApp global = null;

	// 当http请求返回响应时，使用handler处理
	private Handler handler = new Handler() {
		@Override
		public void handleMessage(Message msg) {
			super.handleMessage(msg);
			// 为ListView设置底层数据
			if (!isMore) {
				Logger.d("set");
				adapter.setData(dataList);
				// 为ListView添加adapter
				newList.setAdapter(adapter);
				newList.onRefreshComplete(null, PullToRefreshCallBack.UP);
				//System.out.println("The refresh complete is ture execute!!");
			} else {
				Logger.d("append");
				adapter.appendData(dataList);
				isMore = false;
				//System.out.println("The refresh complete is false executed!!");
				newList.onRefreshComplete(null, PullToRefreshCallBack.DOWN);
			}
			
			int dataSize = adapter.getCount();
			linkArray = new String[dataSize];
			titleArray = new String[dataSize];
			timeArray = new String[dataSize];
			sourceArray = new String[dataSize];
			commentIdArray = new String[dataSize];
			List temp = adapter.getData();
			if (temp != null && temp.size() != 0)
				for (int i = 0; i < temp.size(); i++) {
					Following gai = (Following) temp.get(i);
//					//Log.d(TAG, "articleid in bean:" + gai.getInfoCode());
//					linkArray[i] = gai.getInfoCode();
//					titleArray[i] = gai.getInfoTitle();
//					timeArray[i] = gai.getInfoShowTime();
//					sourceArray[i] = gai.getInfoSource();
//					commentIdArray[i]=gai.getInfoCommentId();
				}
		}
	};

	@Override
	protected void onCreate(Bundle savedInstanceState) {
		this.setContentView(R.layout.ui_mainfriend);

		mBottomMenu = (BottomMenu) findViewById(R.id.mBottomMenu);

		dataList = new ArrayList<Following>();

		newList = (MyListView) this.findViewById(R.id.newList);
		adapter = new FollowingsAdapter(this);
		newList.setAdapter(adapter);

		titleBar = (GTitleBar) this.findViewById(R.id.mTitleBar);

		global = ((MyApp) getApplicationContext());

		totalRecord += RECORD_INCREMENT;
		newList.setOnRefreshListener(this);
		super.onCreate(savedInstanceState);
	}

	/**
	 * 资讯分页请求
	 * 
	 * @param channelId
	 * @param type
	 */
	public void send(int channelId) {
		SpecialRequest request = new SpecialRequest(Url.url_friendshipsfollowinglist_full);
	    request.encoding="utf-8";
	    request.postParams = Url.getFriendshipsfollowinglist(this, MyApp.weiboUser.sina_id, "20", "1");
	    mHttpHandler.sendRequest(request);
		
		dataList = new ArrayList<Following>();
		for(int i=0;i<20;i++){
			Following f = new Following();
			f.setCreateTime("2010-10-" + i);
			f.setUserID("testUsername" + i);
			dataList.add(f);
		}
		handler.sendEmptyMessage(0);
	}

	
	@Override
	public void onItemClick(AdapterView<?> parent, View view, int position,
			long id) {
		int hvCount = newList.getHeaderViewsCount();
		//Log.d(TAG, "position:" + position + " length:" + linkArray.length + "headview:" + hvCount);
		if(position > linkArray.length){
			return;
		}
		Intent intent = new Intent();
		ArrayList<Following> temp = (ArrayList<Following>) adapter
				.getData();
		//String newsID = getID(temp.get(position - 1).getLink());

		intent.putExtra("position", position - hvCount);
		intent.putExtra("title", titleArray);
		intent.putExtra("source", sourceArray);
		intent.putExtra("linkArray", linkArray);
		intent.putExtra("showTime", timeArray);
		intent.putExtra("commentId", commentIdArray);
		intent.setClass(this, ProfileActivity.class);
		Bundle bundle = new Bundle();
		bundle.putString("articleId", linkArray[position-hvCount]);
		intent.putExtras(bundle);
		setGoBack();
		startActivity(intent);
//		adapter.getData().get(position-hvCount).setClicked(true);
		adapter.notifyDataSetChanged();
	}
	
	@Override
	protected void onResume() {
		if(adapter!=null){
			adapter.notifyDatabaseChanged();
		}
		super.onResume();
	}
//	protected int mPageChangeFlag = 0;
	@Override
	protected void initView() {
		// 发出网络请求
		System.currentTimeMillis();
		//sendRequest(pageID);
		infoList = new ArrayList();
		//mPageChangeFlag = 0;
		send(583);
		
		//显示ProgressBar
		startProgress();

		// 设置当ListView中一项被点击时的事件处理函数
		newList.setOnItemClickListener(this);

		// 设置当RefreshListView刷性时的事件处理函数
		// newList.setOnRefreshListener(this);


		initTitleBar();
	}
	 ArrayList<Following> infoList;
	 int totalPage;
	public void httpCompleted(ResponseInterface resp) {
		SpecialResponse response = (SpecialResponse)resp;
		Logger.d(response.content);
//			try {
//				infoList = new ArrayList<Following>();
//				byte[] tmp = ((NewInfoResponse) resp).getData(20);
//				if (tmp != null && tmp.length != 0) {
//					StructResponse sin = new StructResponse(tmp);
//					totalRecord = ((NewInfoResponse) resp).getTotalRecord();
//					//totalPage = totalRecord % 20 == 0 ? totalRecord / 20 : totalRecord / 20 + 1;
//					int count = sin.readInt();
//					//System.out.println("count = " + count);
//					ArrayList<Following> dataArrayList = new ArrayList<Following>();
//					for (int i = 0; i < count; i++) {
//						Following Following = new Following();
//						int recordId = sin.readInt();
//						Following.setInfoCode(recordId + "");
//						String title = sin.readStringFromByteArray(60, "gb2312").trim();
//						if (title.contains("东方视点")) {
//							continue;
//						}
//						Following.setInfoTitle(title);
//						String source = sin.readStringFromByteArray(30, "gb2312").trim();
//						Following.setInfoSource(source);
//						String author = sin.readStringFromByteArray(30, "gb2312").trim();
//						Following.setInfoAuthor(author);
//						int pubDate = sin.readInt();
//						int pubTime = sin.readInt();
//						Following.setInfoShowTime(Drawer.formatDate(pubDate).trim() + " " + Drawer.formatTime(pubTime).trim());
//						String summary = sin.readStringFromByteArray(200, "gb2312").trim();
//						Following.setInfoSimTitle(summary);
//						String commentId = sin.readStringFromByteArray(25, "gb2312").trim();
//						Following.setInfoCommentId(commentId);
//						int vis = sin.readByte();
//						boolean isVisible = vis == 1 ? true : false;
//						if (!isVisible) {
//							continue;
//						}
//						dataArrayList.add(Following);
//						//Log.d(TAG,"" +  Following);
//					}
//				//	refresh();
//					dataList=dataArrayList;
//					handler.sendEmptyMessage(0);
//					closeProgress();
//				}
//			} catch (Exception e) {
//				e.printStackTrace();
//			}
	}
	
	
	

	@Override
	protected void getIntentData() {
		// TODO Auto-generated method stub
	}

	@Override
	protected void setIntentData() {
		// TODO Auto-generated method stub

	}

	// 发送网络请求，请求资讯信息
	private void sendRequest(RequestInterface r) {
//		String myURL = NEWS_URL + pageID;
//		SpecialRequest specialReq = new SpecialRequest(myURL);
//		specialReq.msg_id = MSG_ID;

		if (this.mHttpHandler == null)
			mHttpHandler = new HttpHandler(this, 1000);
		mHttpHandler.sendRequest(r);
	}

	// 设置后退功能
	public void setGoBack() {
		Bundle gobackBundle = new Bundle();
		gobackBundle.putString("back2", getClass().getName());
		GoBack.goBackStack.push(gobackBundle);
	}

	// 捕捉onKeyDown事件
	@Override
	public boolean onKeyDown(int keyCode, KeyEvent event) {
		if (keyCode == KeyEvent.KEYCODE_BACK) {
		}
		return true;
	}


	@Override
	public void onClick(View v) {

	}
	

	public void initTitleBar() {
		
	}

	

	@Override
	public void onRefresh() {
//		pageID = 1;
//		//newList.refresh();
		isMore = false;
		send(583);
//		isMore = false;
	}

	@Override
	public void onGetDown() {
//		++pageID;
		isMore = true;
		send(583);
//		isMore = true;
	}
	
	public void exception(Exception e, HttpHandler handler) {
		requestSuccess = false;
		closeProgress();
		failProgress(e.getMessage());

	}
	
	
}
